import mongoose, { Document, Schema } from 'mongoose';

export interface IUser extends Document {
  name: string;
  email: string;
  password: string;
  phone: string;
  avatar: string;
  role: 'customer' | 'admin' | 'merchant';
  isActive: boolean;
  addresses: {
    name: string;
    phone: string;
    province: string;
    city: string;
    district: string;
    address: string;
    isDefault: boolean;
  }[];
  cart: mongoose.Types.ObjectId[];
  wishlist: mongoose.Types.ObjectId[];
  orders: mongoose.Types.ObjectId[];
  createdAt: Date;
  updatedAt: Date;
}

const UserSchema: Schema = new Schema(
  {
    name: {
      type: String,
      required: [true, '请输入姓名'],
      trim: true,
    },
    email: {
      type: String,
      required: [true, '请输入邮箱'],
      unique: true,
      trim: true,
      lowercase: true,
      match: [
        /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/,
        '请输入有效的邮箱地址',
      ],
    },
    password: {
      type: String,
      required: [true, '请输入密码'],
      minlength: [6, '密码长度不能小于6位'],
    },
    phone: {
      type: String,
      trim: true,
    },
    avatar: {
      type: String,
      default: '',
    },
    role: {
      type: String,
      enum: ['customer', 'admin', 'merchant'],
      default: 'customer',
    },
    isActive: {
      type: Boolean,
      default: true,
    },
    addresses: [
      {
        name: String,
        phone: String,
        province: String,
        city: String,
        district: String,
        address: String,
        isDefault: {
          type: Boolean,
          default: false,
        },
      },
    ],
    cart: [
      {
        type: Schema.Types.ObjectId,
        ref: 'CartItem',
      },
    ],
    wishlist: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Product',
      },
    ],
    orders: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Order',
      },
    ],
  },
  {
    timestamps: true,
  }
);

export default mongoose.model<IUser>('User', UserSchema); 